package key;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Database db = new Database();
	Log log = new Log();

	public void init(ServletConfig config) throws ServletException {
	}

	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String uname = request.getParameter("uname");// 获取输入的昵称
		String passIn = request.getParameter("pass");// 获取输入的密码
		String uid = null;
		if (db.login(uname, passIn)) {
			System.out.println(uname + "已登录系统");
			log.writeIn("Login: " + uname + "登录系统");

			try {
				uid = db.getUid(uname);
			} catch (SQLException e) {
				e.printStackTrace();
				log.writeIn("Login: 查询id失败，数据库内不存在此用户");
			}

			List<Info> timeList = db.createList(uname, uid);
			request.setAttribute("timeList", timeList);// 返回结果集
			log.writeIn("Login: " + uname + "的id为" + uid);

			request.setAttribute("uname", uname);
			request.setAttribute("uid", uid);
			request.getRequestDispatcher("inf.jsp").forward(request, response);
		} else {
			/* 生成错误页面 */
			
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setCharacterEncoding("utf-8");
			out.println("<html>\n<head>\n<title>提示信息</title>\n</head>\n<body>");
			out.println("<script type='text/javascript'>\nconfirm('用户名或密码错误')");
			out.println("window.location.href='index.jsp';\n</script>");
			out.println("</body>\n</html>");
			
//			response.sendRedirect("index.jsp");
//			@SuppressWarnings("unused")
//			Frame fr = new Frame(uname, uid, "昵称密码不匹配或页面出现错误");
			
		}

	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
